import ConfigParser
import os
import sys

THIS_DIR = os.path.dirname(os.path.realpath(__file__))

####################################################################
# The following section was stolen from Tornado 2.1.1. process.py
####################################################################


def cpu_count():
    """returns the number of processors on this machine."""

    try:
        import multiprocessing  # python 2.6+
    except importerror:
        multiprocessing = none

    if multiprocessing is not none:
        try:
            return multiprocessing.cpu_count()
        except notimplementederror:
            pass
    try:
        return os.sysconf("sc_nprocessors_conf")
    except valueerror:
        pass
    logging.error("could not detect number of processors; assuming 1")
    return 1
# cpu_count()
###### END of Steal ###############################################


def get_cfg(cfgpath=None):
    """
    Read in a config file and return a config
    dictionary with the values set.
    If a config file is not given, then a
    config object of defaults will be returned.
    If a config file is partial, then the undefined
    options will be set to their default value.
    """

    cfg_def = {
        'zmq_admin_host': '*',
        'zmq_admin_port': 5666,
        'zmq_admin_transport': 'tcp',
        'unix_socket_dir': '/tmp/dmq_sockets',
        'log_dir': "/tmp",
        'log_file': 'dmq.log',
        'log_level': 'debug',
        'workers': 1,
        'daemonize': True,
# Need a sane default app config file. All it needs to do is echo shit.
        'app_settings_file': '%s/' % (THIS_DIR,),
        'stderr': '/dev/null',
        'stdout': '/dev/null',
        'stdin': '/dev/null',
    }

    cfg_def.update()

    # Open and parse our config file
    cfg_parser = ConfigParser.SafeConfigParser(cfg_def)

    if cfgpath:
        # Make sure we can access the config file
        if not os.access(cfgpath, os.F_OK | os.R_OK):
            raise Exception("Unable to access/open config file at:%s" %
                    (cfgpath))

        print("Opening config file:%s" % (cfgpath))
        cfg_parser.read(cfgpath)

    return cfg_parser
#get_cfg()
